package com.situ.mall.order.listener;


import com.situ.mall.common.constants.MqConstant;
import com.situ.mall.common.util.MultiDelayMessage;
import com.situ.mall.order.service.IOrderInfoService;
import com.situ.mall.pojo.entity.order.OrderInfo;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OrderStatusListener {
	@Autowired
	private IOrderInfoService orderInfoService;
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	@RabbitListener(bindings = @QueueBinding(
			value = @Queue(MqConstant.DELAY_ORDER_QUEUE),
			exchange = @Exchange(name = MqConstant.DELAY_EXCHANGE, delayed = "true"),
			key = MqConstant.DELAY_ORDER_ROUTING_KEY
	))
	public void listenDelayMessage(MultiDelayMessage<Long> msg) {
		System.out.println("OrderStatusListener.listenDelayMessage msg: " + msg);
		//1.获取消息中的订单id
		Long orderId = msg.getData();
		//2.查询订单，判断状态：1是未支付 大于1则是已经支付
		OrderInfo orderInfo = orderInfoService.getById(orderId);
		//订单不存在或者订单已经支付
		if (orderInfo == null || orderInfo.getOrderStatus() > 1) {
			return;
		}
		//3.订单未支付,判断是否还有剩余延时时间
		if (msg.hasNextDelay()) {
			// 有延迟时间，需要重发延迟消息，先获取延迟时间的int值，发送延时消息
			int delayValue = msg.removeNextDelay().intValue();
			rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE, MqConstant.DELAY_ORDER_ROUTING_KEY, msg, new MessagePostProcessor() {
				@Override
				public Message postProcessMessage(Message message) throws AmqpException {
					message.getMessageProperties().setDelay(delayValue);
					return message;
				}
			});
			return;
		}
		//4.没有剩余延时时间,说明订单超时未支付
		orderInfoService.updateStatus(orderId,5);
	}
}
